  <?php defined('SYSPATH') or die('No direct script access.');
  
class Controller_Futbol_Uploadify extends Controller
{
	//public $auth_required = TRUE;
	//public $auth_role     = array('admin');
	
	public function action_uploadify($input)
	{		
		list($type,$id) = explode("-",$input);
		if (!empty($_FILES)) 
		{
			$tempFile = $_FILES['Filedata']['tmp_name']; 
			$targetPath = $_REQUEST['folder'] . '/';
			$targetPath =  str_replace('//','/',$targetPath);
			$targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
			$file_name2 = $_FILES['Filedata']['name'];
			// generowanie nazwy
			$klucz = rand(1,300);
			$klucz .= rand(1,300);
			$klucz .= time();
			$file_ext = strtolower(substr($file_name2, strrpos($file_name2, '.') + 1));
			$file_name = $klucz.".".$file_ext; 
			$input_file = array($tempFile,$file_name);
			
			if($type == 'excerpt')
			{
				//echo Kohana::debug($input_file);exit;
				list($width, $height, $type, $attr) = getimagesize($tempFile);
				$small_width = Kohana::config('appconf.exc_photo_width');
				$small_height = Kohana::config('appconf.exc_photo_height');
				
				if($width > $small_width || $height > $small_height){
					if ($width > $height){ // horizontal
							$n_width=$small_width;
							$n_height = floor(($n_width/$width)*$height);
							// if the height is still > $max_height;
							if($n_height > $small_height){
								$n_height = $small_height;
								$n_width = floor(($n_height/$height)*$width);
							}
						}
					else if($width < $height){ //vertical
							$n_height = $small_height;
							$n_width = floor(($n_height/$height)*$width);
					}
					else if($width == $height){
							$n_height = $small_height;
							$n_width = $small_height;
					}
				}else{
					$n_width = $width;
					$n_height = $height;
				};
				
				
				echo $file_name;
				Image::resize($input_file,$targetPath,$n_height,$n_width);
				
				$model = new Model_Futbol_Pages;
				$news = $model->get_page($id);
				// kasowanie poprzedniej fotki
				if($news['excerpt_photo'] != '')
				{
					$file_del = $_SERVER['DOCUMENT_ROOT']."/".$targetPath."/".$news['excerpt_photo'];
					$file_del = str_replace("//","/",$file_del);
					if(file_exists($file_del))
					{
						unlink($file_del);
					}
				}
				//echo $file_del;
				$model->save_excerpt_photo($id,$file_name);
			}
			else if($type == 'banner')
			{
				$folder = $targetPath;
				$banner_model = new Model_Futbol_Banners;
				$banner_model->insert_banner($id,$file_name2);
				$target_path = $_SERVER['DOCUMENT_ROOT'] .$targetPath.$file_name2;
				$target_path =  str_replace('//','/',$target_path);
				move_uploaded_file($tempFile, $target_path);
			}
		}
	}
}
?>